// pages/user/address/address.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addrList: null,
    prevUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initApp()
  },

  /**
   * init
   */
  initApp: function() {
    let that = this,
        route = getCurrentPages(),
        prevUrl = route[route.length-2]
      wx.showLoading({
        mask: true,
        title: app.globalData.loadText,
      })
      app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
        wx.request({
          url: app.globalData.hostAPI + '/v1/customer/addr?access_token=' + accessToken,
          success: res => {
            if (res.data.status === 1) {
              if(res.data.data.addr == '') {
                wx.hideLoading()
                wx.showModal({
                  title: '提示',
                  content: '暂无地址，是否前去添加',
                  success: res => {
                    if (res) {
                      wx.navigateTo({
                        url: './add/add',
                      })
                    }
                  }
                })
              } else {
                that.setData({
                  addrList: res.data.data.addr,
                  prevUrl: prevUrl.route
                })
                wx.hideLoading()
              }
            }
          }
        })
      })
  },

  addAdress: function() {
    wx.navigateTo({
      url: './add/add',
    })
  },

  /**
   * 修改地址
   */
  updateAddress: function(e) {
    wx.navigateTo({
      url: './add/add?&add_id=' + e.currentTarget.dataset.id,
    })
  },

  /**
   * 删除地址
   */
  delAddress: function(e) {
    let that = this
    wx.showModal({
      title: '警告',
      content: '确认删除',
      success: res => {
        if(res.confirm) {
          wx.showLoading({
            mask: true,
            title: app.globalData.loadText,
          })
          app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
              url: app.globalData.hostAPI + '/v1/addr/delete?access_token=' + accessToken + '&id=' + e.currentTarget.dataset.id,
              success: res => {
                that.initApp()
                wx.hideLoading()
              }
            })
          })
        }
      }
    })
    
  },

  /**
   * 设置默认地址
   */
  setDefault: function(e) {
    let that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/addr/set-default?access_token=' + accessToken,
        data: {
          addr_id: e.currentTarget.dataset.id
        },
        success: res => {
          if(res.data.status === 1) {
            that.initApp()
          }
        }
      })
    })
    
  },

  /**
   * 选择地址返回
   */
  selAddr: function(e) {
    
  }
})